package com.bea.ftd.dashboard.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bea.ftd.common.ValidationException;
import com.bea.ftd.common.dao.RatelimiteInfoRepo;
import com.bea.ftd.common.entity.RatelimiteInfo;
import com.bea.ftd.common.enums.ValidationErrorCode;
import com.bea.ftd.dashboard.service.IGatewayService;
import com.bea.ftd.dashboard.service.IRateLimitInfoService;
import com.bea.ftd.dashboard.validator.BooleanValidator;
import com.bea.ftd.dashboard.validator.CustomTypeValidator;
import com.bea.ftd.dashboard.validator.NumberValidator;
import com.bea.ftd.dashboard.validator.StringValidator;

@Service
public class RateLimitInfoServiceImpl implements IRateLimitInfoService, IGatewayService {
	private Logger LOGGER = LoggerFactory.getLogger(RateLimitInfoServiceImpl.class);

	@Autowired
	private RatelimiteInfoRepo ratelimiteInfoRepo;
	@Autowired
	private StringValidator stringValidator;
	@Autowired
	private BooleanValidator booleanValidator;
	@Autowired
	private NumberValidator numberValidator;
	@Autowired
	private CustomTypeValidator customTypeValidator;

	@Override
	public void addRatelimiteInfo(RatelimiteInfo ratelimiteInfo) throws ValidationException {

		validateInputParams(ratelimiteInfo);
		setCreateOrUpdateTime(ratelimiteInfo, ratelimiteInfoRepo);
		ratelimiteInfoRepo.save(ratelimiteInfo);

	}

	/**
	 * 验证输入参数是否有效
	 * 
	 * @param partnerInfo
	 * @throws ValidationException
	 */
	private void validateInputParams(RatelimiteInfo ratelimiteInfo) throws ValidationException {

		if (stringValidator.isEmptyString(ratelimiteInfo.getApiId())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "API ID不能为空");
		}

		if (!customTypeValidator.isValidRateLimiteInfoType((ratelimiteInfo.getRatelimiteType()))) {
			throw new ValidationException(ValidationErrorCode.INVALID_TYPE, "无效的流量限制类型");
		}
		
		if (!numberValidator.isNonNegtiveNumber(ratelimiteInfo.getRatelimiteSize())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "API ID不能为空");
		}
		
		if (!booleanValidator.isBooleanType(ratelimiteInfo.getDirectTransmit())) {
			throw new ValidationException(ValidationErrorCode.INVALID_BOOLEAN_VALUE, "无效的directTransmit值");
		}
		
		if (!booleanValidator.isBooleanType(ratelimiteInfo.getIsActivated())) {
			throw new ValidationException(ValidationErrorCode.INVALID_BOOLEAN_VALUE, "无效的isActivated值");
		}

	}

	@Override
	public List<RatelimiteInfo> getAllRatelimiteInfos() {
		try {
			return ratelimiteInfoRepo.findAll();
		} catch (Exception e) {
			LOGGER.error("error when querying partnerInfo from database " + e.getMessage());
			return null;
		}
	}
}
